//
//  CommentListViewController.swift
//  jiaoyi
//
//  Created by 易万军 on 2018/10/21.
//  Copyright © 2018 wjk. All rights reserved.
//

import UIKit
import UITextView_Placeholder
import IQKeyboardManagerSwift

class CommentListViewController: UIViewController {

    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var tableView: UITableView!
    var dataArray:NSArray = []
    var id:String!
    override func viewDidLoad() {
        super.viewDidLoad()
        IQKeyboardManager.shared.enable = true
        title = "留言"
        textView.placeholder = "请输入"
        tableView.keyboardDismissMode = .onDrag
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.tableFooterView = UIView()
        tableView.register(UINib.init(nibName: "CommentListTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        loadData()
        // Do any additional setup after loading the view.
    }
    func loadData() -> Void {
        NetWorkRequest(.bidingMessage(id: id)) { (res) -> (Void) in
            if res["code"] as! String == "000000" {
                if res["data"] is NSNull == false {
//                if res["data"]
                    self.dataArray = (res["data"] as? NSArray)!
                    self.tableView.reloadData()
                }
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func post(_ sender: UIButton) {
        self.view.endEditing(true);
        if textView.text!.isEmpty {
            showMessage(message: "请先输入内容")
            return
        }
        
        showHUD()
        NetWorkRequest(.replyMessage(id: id, content: textView.text)) { (res) -> (Void) in
            if res["code"] as! String == "000000" {
                showMessage(message: "成功")
                self.loadData()
                self.textView.text = ""
            }else {
                showMessage(message: res["message"] as! String)
            }
        }
    }
    



}
extension CommentListViewController: UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CommentListTableViewCell
        cell.selectionStyle = .none
        let dic = jsonFormater(data: dataArray[indexPath.row])
        cell.labelDate.text = dic["ent_name"].stringValue
        cell.labelName.text = dic["created_at"].stringValue
        cell.labelContent.text = dic["content"].stringValue
        return cell
    }
}
